package com.jjwxc.jwjskandriod.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.MainActivity;
import com.jjwxc.jwjskandriod.activity.WebActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.model.MonthPriceResponse;
import com.jjwxc.jwjskandriod.model.PayResult;
import com.jjwxc.jwjskandriod.model.RechargeResponse;
import com.jjwxc.jwjskandriod.readActivity.ReadActivity;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

public class BuyMonthlyPop {
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private static Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            if (msg.what == SDK_PAY_FLAG) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                /**
                 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    FFApplication.showToast("你已经成功完成购买");
                    buyMonthPopListener.onOkClick("ok");
                    popWindow.dismiss();
                } else {
                    FFApplication.showToast("支付失败");
                }
            }
        }

        ;
    };
    private static BuyMonthPopListener buyMonthPopListener;
    private static PopupWindow popWindow;

    public static void bugMonthly(View v, Activity context, BuyMonthPopListener monthPopListener) {
        buyMonthPopListener = monthPopListener;
        View view = LayoutInflater.from(context).inflate(R.layout.monthly_buy_pop, null, false);
        TextView tv_queding = view.findViewById(R.id.tv_queding);
        TextView tv_one = view.findViewById(R.id.tv_price_one);
        TextView tv_gmxy = view.findViewById(R.id.tv_gmxy);
        TextView tv_shuku = view.findViewById(R.id.tv_shuku);
        View view_view = view.findViewById(R.id.view_view);
        //1.构造一个PopupWindow，参数依次是加载的 View，宽高
        int height = context.getResources().getDisplayMetrics().heightPixels;// 屏幕的高
        popWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT
                , height + getStatusBarHeight(context), true);
        MobclickAgent.onEvent(context, UMConstant.Event_Reader_Month_Tip);
        popWindow.setAnimationStyle(R.style.ffProg_anim);
        //设置加载动画
        popWindow.setTouchable(true);
        popWindow.setClippingEnabled(false);
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        //设置 popupWindow 显示的位置，参数依次是参照 View，x轴的偏移量，y轴的偏移量
        popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

        Map<String, String> map = new HashMap<>();
        new FFNetWork().post(Url.getMonthSubscribePrice, null, new FFNetWorkCallBack<MonthPriceResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(MonthPriceResponse response) {
                if (response.getCode() == 200) {
                    tv_one.setText(response.getData().get(0).getPrice()/100 + "元/月");
                    map.put("one", response.getData().get(0).getType());
                    map.put("price", map.get("one"));
                }

            }

            @Override
            public boolean onFail(MonthPriceResponse response) {
                return false;
            }
        }, MonthPriceResponse.class, "{\"device\":\"android\"}");

        tv_gmxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setClass(context, WebActivity.class);
                intent.putExtra("WEB_URL", Url.help4);
                intent.putExtra("WEB_NAME", "购买须知");
                context.startActivity(intent);

            }
        });
        tv_shuku.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (context instanceof MainActivity) {
                    Intent intent = new Intent();
                    intent.setAction(MainActivity.RefreshStack);
                    context.sendBroadcast(intent);
                    popWindow.dismiss();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(context, MainActivity.class);
                    intent.putExtra("TYPE", "SDK");
                    context.startActivity(intent);
                }
            }
        });
        tv_queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FFNetWork().post(Url.monthSubscribe, null, new FFNetWorkCallBack<RechargeResponse>() {
                    @Override
                    public void onSuccess(RechargeResponse response) {
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(context);
                                Map<String, String> result = alipay.payV2(response.getData().getOrderStr(), true);
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();

                    }

                    @Override
                    public boolean onFail(RechargeResponse response) {
                        return false;
                    }
                }, RechargeResponse.class, "{\"monthSubscribeType\": \"" + map.get("price") + "\",\"device\":\"android\"}");
            }
        });
        view_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
    }

    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 状态栏高度
     */
    private static int getStatusBarHeight(Context context) {
        // 获得状态栏高度
        @SuppressLint("InternalInsetResource")
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    public interface BuyMonthPopListener {
        void onOkClick(String group);
    }
}
